#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <windows.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <windows.h>

#pragma warning(disable:4996)
#pragma comment(lib,"ws2_32.lib")

using namespace std;

int report_time = 1000;


int main()
{
	time_t start_time, cur_time;
	time(&start_time);//

	int iRet; //返回值
	//初始化
	WORD ver = MAKEWORD(2, 2);
	WSADATA data;
	WSAStartup(ver, &data);

	//创建套接字
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //指定套接字所用的地址簇，AF_INET是IPv4，通信类型指定为流模式SOCK_STREAM，协议为TCP传输协议IPPROTO_TCP

	sockaddr_in sin = {}; //sockaddr_in是IPv4地址结构体，是sockaddr的一种具体实现
	sin.sin_family = AF_INET; //定义地址族ipv4，该属性表示接收本机或其他机器传输
	sin.sin_port = htons(6666); //服务器端口号
	sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //服务器IP地址 本地;
	iRet = connect(serverSocket, (sockaddr*)&sin, sizeof(sockaddr_in)); //和服务器端的socket进行connect，需要服务器端的ip+port


	int input_num;
	cout << "serial number:" << endl;
	cin >> input_num;
	
	Sleep(1000);



	//把输入的数字转换成字符串
	char* str = (char*)malloc(sizeof(char) * 10);
	sprintf(str, "%d", input_num);

	send(serverSocket, str, strlen(str) + 1, 0);



	Sleep(1000);
	char recvbuf[256] = {};
	recv(serverSocket, recvbuf, 256, 0);
	cout << recvbuf << endl;//



	while (true)
	{
		time(&cur_time);//
		if (cur_time - start_time > report_time)
		{
			time(&start_time);//
			char report[100] = "I am alive ";
			strcat(report, str);
			char *addr = nullptr;
			sprintf(addr, "%d", sin.sin_addr.S_un.S_addr);
			strcat(report, addr);
			Sleep(1000);
			send(serverSocket, report, strlen(report) + 1, 0);
		}
	}
		
		
	//关闭socket
	iRet = closesocket(serverSocket);//关闭套接字，微软的接口名称
	if (iRet == SOCKET_ERROR)
	{
		cout << "closesocket fail" << endl;
	}
	else
	{
		cout << "closesocket success" << endl;
	}
	WSACleanup();//清除
}